import { Connection } from 'mongoose';
import { getInstance } from '../../db';
import { userMsgSchema } from '../../schemas/userMsgSchema';

// 获取用户聊天参数
export const getUserMsgList = async (uid: string) => {
  const db: Connection = await getInstance();
  const userMsgModel = db.model('userMsgModel', userMsgSchema);

  const result = await userMsgModel.aggregate([
    {
      $match: {
        $or: {
          toUser: uid,
          fromUser: uid,
        }
      }
    },
    {
      $lookup: {
        from: 'account',
        localField: 'fromUser',
        foreignField: 'uid',
        as: 'account',
      }
    },
    {
      $unwind: {
        path: '$account',
        preserveNullAndEmptyArrays: true,
      }
    },
    // 返回参数
    {
      $project: {
        _id: 1,
        fromUser: 1,
        toUser: 1,
        message: 1,
        type: 1,
        time: 1,
        attachments: 1,
        coverImg: 1,
        profile: "$account.profile",
        username: "$account.username",
      }
    }
  ])

  // console.log(result, '...');

  return result;
}

// 保存用户信息
export const saveUserMsgList = async (params: IAnyObject) => {
  const db: Connection = await getInstance();
  const userMsgModel = db.model('userMsgModel', userMsgSchema);

  console.log(params, '......')

  const result = await userMsgModel.create(params);

  return result;
}

// 删除离线消息
export const deleteUserMsg = async (uid: string) => {
  const db: Connection = await getInstance();
  const userMsgModel = db.model('userMsgModel', userMsgSchema);

  const result = await userMsgModel.remove({uid});

  return result;
}